package main

import (
	"context"
	"flag"
	"fmt"

	"gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/consumer"

	"gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/config"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/jobs/pay"
	serverConfig "gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/server/config"
	serverPayRecharge "gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/server/payrecharge"
	serverPayWithdraw "gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/server/paywithdraw"
	serverRpcslotgame "gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/server/rpcslotgame"
	serverTenantChannel "gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/server/tenantchannel"
	serverUser "gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/server/user"
	serverUserChannel "gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/server/userchannel"
	serverUserWash "gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/server/userwash"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/rpc"
	"gitee.com/liuxuezhan/ar-platform/base-common/app"
	"gitee.com/liuxuezhan/ar-platform/base-common/middleware"
	"gitee.com/liuxuezhan/ar-platform/base-common/xxlJob"
	"github.com/zeromicro/go-zero/core/service"
	"google.golang.org/grpc/reflection"

	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/zrpc"
	"google.golang.org/grpc"
)

var configFile = flag.String("f", "assets-rpc/etc/lxz.yaml", "the config file")

func main() {
	flag.Parse()

	var c config.Config
	conf.MustLoad(*configFile, &c)
	ctx := svc.NewServiceContext(c)

	s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) {
		rpc.RegisterConfigServer(grpcServer, serverConfig.NewConfigServer(ctx))
		rpc.RegisterPayRechargeServer(grpcServer, serverPayRecharge.NewPayRechargeServer(ctx))
		rpc.RegisterPayWithdrawServer(grpcServer, serverPayWithdraw.NewPayWithdrawServer(ctx))
		rpc.RegisterRpcSlotGameServer(grpcServer, serverRpcslotgame.NewRpcSlotGameServer(ctx))
		rpc.RegisterTenantChannelServer(grpcServer, serverTenantChannel.NewTenantChannelServer(ctx))
		rpc.RegisterUserServer(grpcServer, serverUser.NewUserServer(ctx))
		rpc.RegisterUserWashServer(grpcServer, serverUserWash.NewUserWashServer(ctx))
		rpc.RegisterUserChannelServer(grpcServer, serverUserChannel.NewUserChannelServer(ctx))

		if c.Mode == service.DevMode || c.Mode == service.TestMode {
			reflection.Register(grpcServer)
		}
	})
	defer s.Stop()

	// MQ消费
	consumer.RunMQ(ctx)
	app.InitAppServer()

	s.AddUnaryInterceptors(
		middleware.NewRpcAuthMiddleware().Handle(), // 中间件
	)

	// cron job
	jobCli := xxlJob.NewClient(context.Background(), c.XxlJob).Register(pay.NewDepositTimeoutHandler(ctx))
	jobCli.MustStart()

	fmt.Printf("Starting rpc server at %s...\n", c.ListenOn)
	s.Start()
}
